<div class="selenium-notes">
<h1>Web Elements in Selenium</h1>
<p>Web Elements are one of the most important concepts in Selenium WebDriver. A web element is an individual component of a web page such as a textbox, button, checkbox, radio button, link, dropdown, image, label, table, or any other HTML element that a user can interact with or inspect. Selenium WebDriver identifies these elements in the browser and performs actions on them through automation scripts.</p>
<p>Understanding Web Elements is essential for Selenium automation because almost every automated test involves locating an element, identifying its properties, interacting with it, and validating its behavior.</p>
<p>These notes cover Web Elements from basic concepts to advanced handling techniques, including locating elements, WebElement methods, forms, buttons, checkboxes, radio buttons, dropdowns, links, dynamic elements, waits, exceptions, Page Object Model, practical examples, best practices, and interview questions.</p>
<p>For structured Selenium automation learning and practical training, visit <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">JustAcademy Selenium Training</a> and <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for a Course Demo</a>.</p>
<hr>
<h2>1. What is a Web Element?</h2>
<p>A Web Element is an HTML element present on a web page that can be identified and interacted with using Selenium WebDriver. Examples include input fields, buttons, links, checkboxes, radio buttons, dropdowns, images, paragraphs, headings, tables, and forms.</p>
<pre><code><input type="text" id="username">
<button id="login">Login</button>
<a href="/home">Home</a></code></pre>
<p>In the above HTML, the input, button, and anchor elements are Web Elements from the perspective of Selenium.</p>
<hr>
<h2>2. Why Web Elements are Important in Selenium</h2>
<ul>
<li>They allow Selenium to interact with web pages.</li>
<li>They are used to enter data into forms.</li>
<li>They allow automated clicks on buttons and links.</li>
<li>They allow testers to select checkboxes and radio buttons.</li>
<li>They allow testers to read visible text.</li>
<li>They allow validation of element attributes.</li>
<li>They help automate complete user workflows.</li>
<li>They are essential for functional and regression testing.</li>
</ul>
<hr>
<h2>3. Common Web Elements</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Web Element</th><th>HTML Tag</th><th>Example</th></tr>
<tr><td>Text Field</td><td><input></td><td>Username</td></tr>
<tr><td>Password Field</td><td><input type="password"></td><td>Password</td></tr>
<tr><td>Button</td><td><button></td><td>Login</td></tr>
<tr><td>Link</td><td><a></td><td>Home</td></tr>
<tr><td>Checkbox</td><td><input type="checkbox"></td><td>Remember Me</td></tr>
<tr><td>Radio Button</td><td><input type="radio"></td><td>Male/Female</td></tr>
<tr><td>Dropdown</td><td><select></td><td>Country</td></tr>
<tr><td>Image</td><td><img></td><td>Logo</td></tr>
<tr><td>Heading</td><td><h1> to <h6></td><td>Page Title</td></tr>
<tr><td>Paragraph</td><td><p></td><td>Description</td></tr>
<tr><td>Text Area</td><td><textarea></td><td>Comments</td></tr>
<tr><td>Form</td><td><form></td><td>Registration Form</td></tr>
</table>
<hr>
<h2>4. HTML Structure of a Web Element</h2>
<p>A typical HTML element contains a tag name, attributes, and content.</p>
<pre><code><input type="text" id="username" name="user" class="form-control"></code></pre>
<p>In this example:</p>
<ul>
<li><strong>input</strong> is the tag name.</li>
<li><strong>type</strong> is an attribute.</li>
<li><strong>text</strong> is the attribute value.</li>
<li><strong>id</strong> is an attribute.</li>
<li><strong>username</strong> is the ID value.</li>
<li><strong>name</strong> is another attribute.</li>
<li><strong>user</strong> is the name value.</li>
<li><strong>class</strong> is another attribute.</li>
</ul>
<hr>
<h2>5. WebElement Interface</h2>
<p>In Selenium Java, WebElement is an interface provided by Selenium WebDriver. It represents an HTML element in the browser.</p>
<pre><code>WebElement username = driver.findElement(By.id("username"));</code></pre>
<p>The WebElement object can then be used to perform actions such as clicking, typing, reading text, checking visibility, and checking whether an element is selected.</p>
<hr>
<h2>6. Finding a Web Element</h2>
<p>Before Selenium can interact with an element, it must first locate that element on the page.</p>
<pre><code>WebElement element = driver.findElement(By.id("username"));</code></pre>
<p>The <strong>findElement()</strong> method searches the current page and returns the first matching WebElement.</p>
<hr>
<h2>7. Selenium Locators</h2>
<p>Selenium provides several locator strategies for identifying Web Elements.</p>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Locator</th><th>Syntax</th><th>Usage</th></tr>
<tr><td>ID</td><td>By.id()</td><td>Find by id attribute</td></tr>
<tr><td>Name</td><td>By.name()</td><td>Find by name attribute</td></tr>
<tr><td>Class Name</td><td>By.className()</td><td>Find by class attribute</td></tr>
<tr><td>Tag Name</td><td>By.tagName()</td><td>Find by HTML tag</td></tr>
<tr><td>Link Text</td><td>By.linkText()</td><td>Find exact link text</td></tr>
<tr><td>Partial Link Text</td><td>By.partialLinkText()</td><td>Find partial link text</td></tr>
<tr><td>CSS Selector</td><td>By.cssSelector()</td><td>Find using CSS</td></tr>
<tr><td>XPath</td><td>By.xpath()</td><td>Find using XPath</td></tr>
</table>
<hr>
<h2>8. Locating Elements by ID</h2>
<p>ID is generally a convenient locator when the element has a unique and stable ID.</p>
<pre><code>WebElement username = driver.findElement(By.id("username"));
username.sendKeys("admin");</code></pre>
<p>HTML:</p>
<pre><code><input type="text" id="username"></code></pre>
<hr>
<h2>9. Locating Elements by Name</h2>
<pre><code>WebElement password = driver.findElement(By.name("password"));
password.sendKeys("Admin@123");</code></pre>
<p>HTML:</p>
<pre><code><input type="password" name="password"></code></pre>
<hr>
<h2>10. Locating Elements by Class Name</h2>
<pre><code>WebElement button = driver.findElement(By.className("login-button"));</code></pre>
<p>HTML:</p>
<pre><code><button class="login-button">Login</button></code></pre>
<p>When an element contains multiple classes, Selenium's className locator should target one complete class token rather than a string containing spaces.</p>
<hr>
<h2>11. Locating Elements by Tag Name</h2>
<pre><code>List<WebElement> links = driver.findElements(By.tagName("a"));</code></pre>
<p>Tag-name locators are useful when working with groups of similar elements.</p>
<hr>
<h2>12. Locating Elements by Link Text</h2>
<pre><code>WebElement home = driver.findElement(By.linkText("Home"));
home.click();</code></pre>
<p>This works when the exact visible text of the anchor is known.</p>
<hr>
<h2>13. Locating Elements by Partial Link Text</h2>
<pre><code>WebElement link = driver.findElement(By.partialLinkText("Selenium"));
link.click();</code></pre>
<p>Partial link text can be useful when the complete link text is dynamic or lengthy.</p>
<hr>
<h2>14. Locating Elements Using CSS Selector</h2>
<pre><code>WebElement username = driver.findElement(By.cssSelector("#username"));
WebElement password = driver.findElement(By.cssSelector("input[name='password']"));
WebElement login = driver.findElement(By.cssSelector(".login-button"));</code></pre>
<p>CSS selectors are concise and powerful for locating elements.</p>
<hr>
<h2>15. Locating Elements Using XPath</h2>
<pre><code>WebElement username = driver.findElement(By.xpath("//input[@id='username']"));
WebElement login = driver.findElement(By.xpath("//button[text()='Login']"));</code></pre>
<p>XPath is particularly useful for complex and dynamic element structures.</p>
<hr>
<h2>16. findElement() vs findElements()</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>findElement()</th><th>findElements()</th></tr>
<tr><td>Returns one WebElement</td><td>Returns a List of WebElements</td></tr>
<tr><td>Returns the first matching element</td><td>Returns all matching elements</td></tr>
<tr><td>Throws NoSuchElementException when no match exists</td><td>Returns an empty list when no match exists</td></tr>
<tr><td>Useful for individual controls</td><td>Useful for collections of elements</td></tr>
</table>
<pre><code>WebElement login = driver.findElement(By.id("login"));
List<WebElement> buttons = driver.findElements(By.tagName("button"));</code></pre>
<hr>
<h2>17. click() Method</h2>
<p>The click() method is used to click a Web Element.</p>
<pre><code>WebElement login = driver.findElement(By.id("login"));
login.click();</code></pre>
<p>It can be used with buttons, links, checkboxes, radio buttons, menu items, and other clickable elements.</p>
<hr>
<h2>18. sendKeys() Method</h2>
<p>The sendKeys() method is used to enter keyboard input into a text field or other editable element.</p>
<pre><code>WebElement username = driver.findElement(By.id("username"));
username.sendKeys("admin");</code></pre>
<hr>
<h2>19. clear() Method</h2>
<p>The clear() method removes existing text from an editable field.</p>
<pre><code>WebElement username = driver.findElement(By.id("username"));
username.clear();
username.sendKeys("newUser");</code></pre>
<hr>
<h2>20. getText() Method</h2>
<p>The getText() method returns the visible text of an element.</p>
<pre><code>WebElement message = driver.findElement(By.id("message"));
String text = message.getText();
System.out.println(text);</code></pre>
<p>It is commonly used for validation.</p>
<hr>
<h2>21. getAttribute() Method</h2>
<p>The getAttribute() method is used to retrieve the value of an HTML attribute.</p>
<pre><code>WebElement username = driver.findElement(By.id("username"));
String value = username.getAttribute("value");
System.out.println(value);</code></pre>
<p>Common attributes include id, name, class, href, value, title, placeholder, src, and aria-label.</p>
<hr>
<h2>22. getDomAttribute() and getDomProperty()</h2>
<p>Modern Selenium versions also provide methods for distinguishing DOM attributes and DOM properties.</p>
<pre><code>String attribute = element.getDomAttribute("value");
String property = element.getDomProperty("value");</code></pre>
<p>This distinction can be useful when working with dynamic forms where an HTML attribute and the current DOM property may have different values.</p>
<hr>
<h2>23. isDisplayed() Method</h2>
<p>isDisplayed() checks whether an element is currently displayed on the page.</p>
<pre><code>WebElement element = driver.findElement(By.id("message"));
if (element.isDisplayed()) {
System.out.println("Element is visible");
}</code></pre>
<hr>
<h2>24. isEnabled() Method</h2>
<p>isEnabled() checks whether an element is enabled for interaction.</p>
<pre><code>WebElement button = driver.findElement(By.id("submit"));
if (button.isEnabled()) {
button.click();
}</code></pre>
<hr>
<h2>25. isSelected() Method</h2>
<p>isSelected() checks whether selectable elements such as checkboxes and radio buttons are selected.</p>
<pre><code>WebElement checkbox = driver.findElement(By.id("remember"));
if (!checkbox.isSelected()) {
checkbox.click();
}</code></pre>
<hr>
<h2>26. submit() Method</h2>
<p>The submit() method can submit a form associated with an element. However, using the actual submit button with click() is often clearer in modern automation scripts.</p>
<pre><code>WebElement form = driver.findElement(By.id("loginForm"));
form.submit();</code></pre>
<hr>
<h2>27. WebElement Method Summary</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Method</th><th>Purpose</th></tr>
<tr><td>click()</td><td>Clicks an element</td></tr>
<tr><td>sendKeys()</td><td>Enters text or keyboard input</td></tr>
<tr><td>clear()</td><td>Clears editable text</td></tr>
<tr><td>getText()</td><td>Gets visible text</td></tr>
<tr><td>getAttribute()</td><td>Gets an attribute value</td></tr>
<tr><td>getDomAttribute()</td><td>Gets a DOM attribute</td></tr>
<tr><td>getDomProperty()</td><td>Gets a DOM property</td></tr>
<tr><td>isDisplayed()</td><td>Checks visibility</td></tr>
<tr><td>isEnabled()</td><td>Checks whether element is enabled</td></tr>
<tr><td>isSelected()</td><td>Checks selection state</td></tr>
<tr><td>submit()</td><td>Submits a form</td></tr>
</table>
<hr>
<h2>28. Handling Text Fields</h2>
<pre><code>WebElement username = driver.findElement(By.id("username"));
username.clear();
username.sendKeys("testuser");</code></pre>
<p>Text fields are commonly used for usernames, search boxes, names, email addresses, phone numbers, and other inputs.</p>
<hr>
<h2>29. Handling Password Fields</h2>
<pre><code>WebElement password = driver.findElement(By.id("password"));
password.sendKeys("Test@123");</code></pre>
<p>Password fields behave similarly to normal text fields, but browsers typically hide the entered characters.</p>
<hr>
<h2>30. Handling Text Areas</h2>
<pre><code>WebElement comments = driver.findElement(By.id("comments"));
comments.sendKeys("This is a Selenium automation test.");</code></pre>
<hr>
<h2>31. Handling Buttons</h2>
<pre><code>WebElement loginButton = driver.findElement(By.id("login"));
loginButton.click();</code></pre>
<p>Buttons are frequently used for login, registration, search, submit, checkout, save, update, and delete operations.</p>
<hr>
<h2>32. Handling Links</h2>
<pre><code>WebElement home = driver.findElement(By.linkText("Home"));
home.click();</code></pre>
<p>Links are usually represented by the HTML anchor tag.</p>
<hr>
<h2>33. Handling Checkboxes</h2>
<pre><code>WebElement checkbox = driver.findElement(By.id("terms"));
if (!checkbox.isSelected()) {
checkbox.click();
}</code></pre>
<p>Checking isSelected() before clicking prevents accidentally unchecking an already selected checkbox.</p>
<hr>
<h2>34. Handling Radio Buttons</h2>
<pre><code>WebElement male = driver.findElement(By.id("male"));
if (!male.isSelected()) {
male.click();
}</code></pre>
<hr>
<h2>35. Handling Standard Dropdowns</h2>
<p>For a standard HTML select element, Selenium provides the Select class.</p>
<pre><code>WebElement country = driver.findElement(By.id("country"));
Select select = new Select(country);
select.selectByVisibleText("India");</code></pre>
<hr>
<h2>36. Handling Images</h2>
<p>Images may not always require direct interaction, but Selenium can validate their attributes such as src and alt.</p>
<pre><code>WebElement logo = driver.findElement(By.id("logo"));
String source = logo.getAttribute("src");
String altText = logo.getAttribute("alt");</code></pre>
<hr>
<h2>37. Handling Labels</h2>
<pre><code>WebElement label = driver.findElement(By.cssSelector("label[for='username']"));
System.out.println(label.getText());</code></pre>
<p>Labels can be validated to ensure that form fields have appropriate descriptions.</p>
<hr>
<h2>38. Handling Tables</h2>
<p>Tables usually contain rows and columns represented by tr, th, and td elements.</p>
<pre><code>List<WebElement> rows = driver.findElements(By.cssSelector("table tbody tr"));
System.out.println("Rows: " + rows.size());</code></pre>
<hr>
<h2>39. Reading Multiple Web Elements</h2>
<p>findElements() can be used to retrieve a collection of matching Web Elements.</p>
<pre><code>List<WebElement> buttons = driver.findElements(By.tagName("button"));
for (WebElement button : buttons) {
System.out.println(button.getText());
}</code></pre>
<hr>
<h2>40. Iterating Through Web Elements</h2>
<pre><code>List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement link : links) {
System.out.println(link.getText());
}</code></pre>
<hr>
<h2>41. Validating All Links on a Page</h2>
<pre><code>List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement link : links) {
String text = link.getText();
String href = link.getAttribute("href");
System.out.println(text + " - " + href);
}</code></pre>
<hr>
<h2>42. Web Element Visibility</h2>
<p>An element can exist in the DOM but not be visible to the user. Selenium provides isDisplayed() to check whether the element is displayed.</p>
<pre><code>if (element.isDisplayed()) {
System.out.println("Element is displayed");
}</code></pre>
<hr>
<h2>43. Web Element Enabled State</h2>
<p>Some controls are visible but disabled. Use isEnabled() to verify whether the element can be interacted with.</p>
<pre><code>if (element.isEnabled()) {
System.out.println("Element is enabled");
} else {
System.out.println("Element is disabled");
}</code></pre>
<hr>
<h2>44. Web Element Selected State</h2>
<p>Use isSelected() for checkboxes, radio buttons, and selectable controls.</p>
<pre><code>if (element.isSelected()) {
System.out.println("Selected");
} else {
System.out.println("Not selected");
}</code></pre>
<hr>
<h2>45. Web Element Size</h2>
<p>Selenium can retrieve the size of a Web Element.</p>
<pre><code>Dimension size = element.getSize();
System.out.println(size.getWidth());
System.out.println(size.getHeight());</code></pre>
<hr>
<h2>46. Web Element Location</h2>
<p>The location of an element can be obtained using getLocation().</p>
<pre><code>Point location = element.getLocation();
System.out.println(location.getX());
System.out.println(location.getY());</code></pre>
<hr>
<h2>47. Web Element Rectangle</h2>
<p>The getRect() method provides information about the element's location and dimensions.</p>
<pre><code>Rectangle rect = element.getRect();
System.out.println(rect.getX());
System.out.println(rect.getY());
System.out.println(rect.getWidth());
System.out.println(rect.getHeight());</code></pre>
<hr>
<h2>48. Web Element Tag Name</h2>
<pre><code>String tag = element.getTagName();
System.out.println(tag);</code></pre>
<p>This can be useful when validating the HTML type of a located element.</p>
<hr>
<h2>49. Web Element Accessibility Information</h2>
<p>Modern web applications often use accessibility attributes such as aria-label, aria-describedby, and role.</p>
<pre><code>String label = element.getAttribute("aria-label");
String role = element.getAttribute("role");</code></pre>
<p>These attributes can also provide useful information for identifying and validating accessible UI components.</p>
<hr>
<h2>50. Dynamic Web Elements</h2>
<p>Dynamic Web Elements are elements whose attributes, location, text, or availability can change during page execution.</p>
<pre><code><button id="button_82931">Submit</button></code></pre>
<p>If the ID changes every time the page loads, a locator based only on that dynamic ID may become unreliable.</p>
<hr>
<h2>51. Handling Dynamic IDs</h2>
<p>Instead of depending on the entire dynamic ID, use stable attributes or XPath functions.</p>
<pre><code>WebElement button = driver.findElement(
By.xpath("//button[contains(@id,'button_')]")
);</code></pre>
<hr>
<h2>52. XPath contains()</h2>
<pre><code>By.xpath("//input[contains(@id,'user')]")</code></pre>
<p>The contains() function is useful when only part of an attribute value is stable.</p>
<hr>
<h2>53. XPath starts-with()</h2>
<pre><code>By.xpath("//input[starts-with(@id,'user_')]")</code></pre>
<p>starts-with() can be used when an attribute consistently begins with a known value.</p>
<hr>
<h2>54. XPath text()</h2>
<pre><code>By.xpath("//button[text()='Login']")</code></pre>
<p>text() can locate elements using their visible text.</p>
<hr>
<h2>55. XPath normalize-space()</h2>
<pre><code>By.xpath("//button[normalize-space()='Login']")</code></pre>
<p>normalize-space() helps when extra spaces or line breaks exist around visible text.</p>
<hr>
<h2>56. Parent-Child Element Relationship</h2>
<p>Web pages are structured as a hierarchy of parent and child elements.</p>
<pre><code><div class="login-form">
<input id="username">
<input id="password">
<button>Login</button>
</div></code></pre>
<p>XPath can navigate through these relationships.</p>
<pre><code>By.xpath("//div[@class='login-form']//button")</code></pre>
<hr>
<h2>57. Sibling Elements</h2>
<p>XPath can also be used to locate elements related to sibling elements.</p>
<pre><code>By.xpath("//label[text()='Username']/following-sibling::input")</code></pre>
<hr>
<h2>58. Handling Nested Web Elements</h2>
<p>Sometimes an element is nested inside another element. You can first locate the parent and then locate the child.</p>
<pre><code>WebElement form = driver.findElement(By.id("loginForm"));
WebElement username = form.findElement(By.name("username"));
username.sendKeys("admin");</code></pre>
<hr>
<h2>59. WebElement and JavaScript</h2>
<p>Selenium normally interacts with elements through WebDriver commands. JavaScript can be used when standard interaction is insufficient, but it should not be the default approach.</p>
<pre><code>JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", element);</code></pre>
<hr>
<h2>60. Scrolling to a Web Element</h2>
<pre><code>JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView(true);", element);</code></pre>
<p>Scrolling can help when an element is outside the currently visible viewport.</p>
<hr>
<h2>61. Actions Class with Web Elements</h2>
<p>The Actions class is useful for advanced mouse and keyboard interactions such as hover, drag-and-drop, right-click, double-click, and keyboard combinations.</p>
<pre><code>Actions actions = new Actions(driver);
actions.moveToElement(element).perform();</code></pre>
<hr>
<h2>62. Hover Over an Element</h2>
<pre><code>Actions actions = new Actions(driver);
actions.moveToElement(menu).perform();</code></pre>
<hr>
<h2>63. Double Click</h2>
<pre><code>Actions actions = new Actions(driver);
actions.doubleClick(element).perform();</code></pre>
<hr>
<h2>64. Right Click</h2>
<pre><code>Actions actions = new Actions(driver);
actions.contextClick(element).perform();</code></pre>
<hr>
<h2>65. Drag and Drop</h2>
<pre><code>Actions actions = new Actions(driver);
actions.dragAndDrop(source, target).perform();</code></pre>
<hr>
<h2>66. Keyboard Interaction</h2>
<pre><code>element.sendKeys(Keys.ENTER);
element.sendKeys(Keys.TAB);</code></pre>
<hr>
<h2>67. Explicit Wait for Web Elements</h2>
<p>Web applications often load elements asynchronously. Explicit waits allow Selenium to wait for a specific condition.</p>
<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement login = wait.until(
ExpectedConditions.elementToBeClickable(By.id("login"))
);
login.click();</code></pre>
<hr>
<h2>68. Visibility Wait</h2>
<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("message"))
);</code></pre>
<hr>
<h2>69. Presence vs Visibility</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Condition</th><th>Meaning</th></tr>
<tr><td>presenceOfElementLocated</td><td>Element exists in the DOM</td></tr>
<tr><td>visibilityOfElementLocated</td><td>Element exists and is visible</td></tr>
<tr><td>elementToBeClickable</td><td>Element is visible and enabled for clicking</td></tr>
<tr><td>invisibilityOfElementLocated</td><td>Element becomes invisible or unavailable</td></tr>
</table>
<hr>
<h2>70. Implicit Wait</h2>
<p>An implicit wait tells WebDriver to wait for a specified amount of time when searching for elements.</p>
<pre><code>driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));</code></pre>
<p>Implicit waits apply broadly to element searches. Avoid mixing implicit and explicit waits without understanding their interaction.</p>
<hr>
<h2>71. Fluent Wait</h2>
<p>FluentWait allows customized polling intervals and exception handling.</p>
<pre><code>Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);</code></pre>
<hr>
<h2>72. NoSuchElementException</h2>
<p>NoSuchElementException occurs when Selenium cannot find the requested element.</p>
<pre><code>WebElement element = driver.findElement(By.id("missingElement"));</code></pre>
<p>Common causes include incorrect locators, wrong page, timing problems, iframe context, or dynamic content.</p>
<hr>
<h2>73. StaleElementReferenceException</h2>
<p>A stale element exception occurs when the previously located WebElement is no longer attached to the current DOM.</p>
<p>This can happen after page refreshes, DOM updates, navigation, or JavaScript-driven changes.</p>
<pre><code>WebElement element = driver.findElement(By.id("username"));
driver.navigate().refresh();
element.sendKeys("admin");</code></pre>
<p>In such cases, locate the element again after the DOM has changed.</p>
<hr>
<h2>74. ElementNotInteractableException</h2>
<p>This exception can occur when Selenium finds an element but cannot interact with it in its current state.</p>
<p>Possible causes include hidden elements, disabled elements, incorrect timing, overlays, or incorrect page state.</p>
<hr>
<h2>75. ElementClickInterceptedException</h2>
<p>This exception can occur when another element or overlay blocks the target element.</p>
<p>Possible solutions include waiting for the overlay to disappear, scrolling appropriately, or waiting until the target becomes clickable.</p>
<hr>
<h2>76. InvalidSelectorException</h2>
<p>This exception occurs when a CSS selector or XPath expression is syntactically invalid.</p>
<pre><code>By.xpath("//button[@id='login'")</code></pre>
<p>The above XPath is incomplete and can cause a selector error.</p>
<hr>
<h2>77. Handling Elements Inside an iframe</h2>
<p>An element inside an iframe cannot normally be accessed until Selenium switches into the iframe context.</p>
<pre><code>WebElement frame = driver.findElement(By.id("paymentFrame"));
driver.switchTo().frame(frame);
WebElement card = driver.findElement(By.id("cardNumber"));
card.sendKeys("4111111111111111");
driver.switchTo().defaultContent();</code></pre>
<hr>
<h2>78. Handling Elements Inside Nested Frames</h2>
<p>For nested iframes, Selenium must switch into the correct frame hierarchy before locating the target element.</p>
<pre><code>driver.switchTo().frame("outerFrame");
driver.switchTo().frame("innerFrame");
WebElement element = driver.findElement(By.id("target"));
driver.switchTo().defaultContent();</code></pre>
<hr>
<h2>79. Web Elements in Multiple Windows</h2>
<p>When a link or button opens another window or tab, Selenium must switch to the appropriate window before interacting with its elements.</p>
<pre><code>String originalWindow = driver.getWindowHandle();
for (String window : driver.getWindowHandles()) {
if (!window.equals(originalWindow)) {
driver.switchTo().window(window);
break;
}
}
WebElement element = driver.findElement(By.id("target"));
element.click();</code></pre>
<hr>
<h2>80. Web Elements in Shadow DOM</h2>
<p>Modern applications may use Shadow DOM to encapsulate HTML elements. Selenium provides APIs for accessing shadow roots.</p>
<pre><code>WebElement host = driver.findElement(By.cssSelector("my-component"));
SearchContext shadowRoot = host.getShadowRoot();
WebElement button = shadowRoot.findElement(By.cssSelector("button"));
button.click();</code></pre>
<hr>
<h2>81. Hidden Elements</h2>
<p>An element may exist in the DOM but remain hidden from the user.</p>
<pre><code>WebElement element = driver.findElement(By.id("hiddenElement"));
System.out.println(element.isDisplayed());</code></pre>
<p>Normally, Selenium should interact with elements in the same way a real user can interact with them.</p>
<hr>
<h2>82. Disabled Elements</h2>
<pre><code>WebElement button = driver.findElement(By.id("submit"));
System.out.println(button.isEnabled());</code></pre>
<p>Always validate the enabled state when the application intentionally disables controls until required conditions are met.</p>
<hr>
<h2>83. Web Element Attribute Validation</h2>
<pre><code>String placeholder = element.getAttribute("placeholder");
String className = element.getAttribute("class");
String id = element.getAttribute("id");
System.out.println(placeholder);
System.out.println(className);
System.out.println(id);</code></pre>
<hr>
<h2>84. Validating Element Text</h2>
<pre><code>String actualText = element.getText();
String expectedText = "Login successful";
Assert.assertEquals(actualText, expectedText);</code></pre>
<hr>
<h2>85. Validating Element Visibility with TestNG</h2>
<pre><code>Assert.assertTrue(element.isDisplayed());</code></pre>
<hr>
<h2>86. Validating Element State</h2>
<pre><code>Assert.assertTrue(button.isEnabled());
Assert.assertTrue(checkbox.isSelected());</code></pre>
<hr>
<h2>87. Web Elements and Page Object Model</h2>
<p>In the Page Object Model, Web Elements and their interactions are organized inside page classes. This reduces duplication and makes test scripts easier to maintain.</p>
<pre><code>public class LoginPage {
private WebDriver driver;
private By username = By.id("username");
private By password = By.id("password");
private By loginButton = By.id("login");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void enterUsername(String value) {
driver.findElement(username).sendKeys(value);
}
public void enterPassword(String value) {
driver.findElement(password).sendKeys(value);
}
public void clickLogin() {
driver.findElement(loginButton).click();
}
}</code></pre>
<hr>
<h2>88. Web Elements with PageFactory</h2>
<p>PageFactory can be used to declare page elements using annotations.</p>
<pre><code>public class LoginPage {
@FindBy(id = "username")
WebElement username;
@FindBy(id = "password")
WebElement password;
@FindBy(id = "login")
WebElement loginButton;
public void login(String user, String pass) {
username.sendKeys(user);
password.sendKeys(pass);
loginButton.click();
}
}</code></pre>
<p>Many modern Selenium projects prefer explicit locators and methods, while PageFactory remains a pattern you may encounter in existing frameworks.</p>
<hr>
<h2>89. Reusable Web Element Methods</h2>
<p>Reusable utility methods can reduce repetitive code.</p>
<pre><code>public void enterText(By locator, String text) {
WebElement element = driver.findElement(locator);
element.clear();
element.sendKeys(text);
}
public void clickElement(By locator) {
driver.findElement(locator).click();
}</code></pre>
<hr>
<h2>90. Generic Web Element Utility Class</h2>
<pre><code>public class ElementUtils {
private WebDriver driver;
public ElementUtils(WebDriver driver) {
this.driver = driver;
}
public void click(By locator) {
driver.findElement(locator).click();
}
public void type(By locator, String text) {
WebElement element = driver.findElement(locator);
element.clear();
element.sendKeys(text);
}
public String getText(By locator) {
return driver.findElement(locator).getText();
}
public boolean isDisplayed(By locator) {
return driver.findElement(locator).isDisplayed();
}
}</code></pre>
<hr>
<h2>91. Locator Strategy for Web Elements</h2>
<p>A good locator should be stable, readable, unique, and maintainable.</p>
<ol>
<li>Prefer stable unique IDs when available.</li>
<li>Use meaningful attributes such as name or data-testid.</li>
<li>Use CSS selectors when they are simple and stable.</li>
<li>Use XPath when relationships or complex conditions are required.</li>
<li>Avoid unnecessarily long XPath expressions.</li>
<li>Avoid relying on frequently changing classes.</li>
<li>Avoid locators that depend on screen position.</li>
</ol>
<hr>
<h2>92. data-testid for Web Elements</h2>
<p>Applications designed for automated testing may provide stable attributes such as data-testid.</p>
<pre><code><button data-testid="login-button">Login</button></code></pre>
<pre><code>WebElement login = driver.findElement(
By.cssSelector("[data-testid='login-button']")
);</code></pre>
<hr>
<h2>93. Handling Dynamic Web Applications</h2>
<p>Modern applications often use AJAX, JavaScript, React, Angular, Vue, and other frameworks. Elements may appear, disappear, or change without a complete page reload.</p>
<p>Reliable automation requires appropriate synchronization, stable locators, and correct handling of DOM updates.</p>
<hr>
<h2>94. Web Element Synchronization</h2>
<p>Synchronization means coordinating Selenium execution with the application's actual state.</p>
<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement button = wait.until(
ExpectedConditions.elementToBeClickable(By.id("submit"))
);
button.click();</code></pre>
<hr>
<h2>95. Avoiding Thread.sleep()</h2>
<p>Thread.sleep() pauses execution for a fixed duration regardless of whether the element is ready.</p>
<pre><code>Thread.sleep(5000);</code></pre>
<p>Explicit waits are generally more flexible because they wait for a meaningful application condition rather than an arbitrary amount of time.</p>
<hr>
<h2>96. Web Elements and AJAX</h2>
<p>AJAX-based applications can update individual portions of a page without refreshing the entire browser page. Selenium scripts should wait for the specific element or state required before interacting.</p>
<hr>
<h2>97. Web Elements and Loading Spinners</h2>
<p>Loading overlays can block interaction with elements.</p>
<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
wait.until(ExpectedConditions.invisibilityOfElementLocated(
By.cssSelector(".loading-spinner")
));
WebElement button = driver.findElement(By.id("submit"));
button.click();</code></pre>
<hr>
<h2>98. Web Elements and Modals</h2>
<p>Modal dialogs may contain buttons, inputs, dropdowns, and other elements. Locate the modal or wait for it to become visible before interacting with its child elements.</p>
<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement modal = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("loginModal"))
);
modal.findElement(By.id("username")).sendKeys("admin");
modal.findElement(By.id("password")).sendKeys("Admin@123");</code></pre>
<hr>
<h2>99. Web Elements and Tooltips</h2>
<p>Tooltips may appear after hovering over an element.</p>
<pre><code>Actions actions = new Actions(driver);
actions.moveToElement(element).perform();
WebElement tooltip = driver.findElement(By.cssSelector(".tooltip"));
System.out.println(tooltip.getText());</code></pre>
<hr>
<h2>100. Web Elements and Auto-Suggest</h2>
<p>Search boxes may display suggestions dynamically as the user types.</p>
<pre><code>WebElement search = driver.findElement(By.id("search"));
search.sendKeys("Selenium");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement suggestion = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.xpath("//li[contains(.,'Selenium')]")
)
);
suggestion.click();</code></pre>
<hr>
<h2>101. Web Elements and Calendar Controls</h2>
<p>Calendar widgets may contain buttons, month selectors, year selectors, and date elements.</p>
<pre><code>WebElement date = driver.findElement(
By.xpath("//button[normalize-space()='15']")
);
date.click();</code></pre>
<hr>
<h2>102. Web Elements and Search Results</h2>
<pre><code>List<WebElement> results = driver.findElements(
By.cssSelector(".search-result")
);
for (WebElement result : results) {
System.out.println(result.getText());
}</code></pre>
<hr>
<h2>103. Web Elements in E-Commerce Applications</h2>
<p>E-commerce applications contain many types of Web Elements such as product cards, search boxes, filters, buttons, carts, checkout forms, and payment controls.</p>
<pre><code>WebElement search = driver.findElement(By.id("search"));
search.sendKeys("Laptop");
WebElement searchButton = driver.findElement(By.id("searchButton"));
searchButton.click();</code></pre>
<hr>
<h2>104. Web Elements in Login Automation</h2>
<pre><code>WebElement username = driver.findElement(By.id("username"));
WebElement password = driver.findElement(By.id("password"));
WebElement login = driver.findElement(By.id("login"));
username.sendKeys("admin");
password.sendKeys("Admin@123");
login.click();</code></pre>
<hr>
<h2>105. Web Elements in Registration Automation</h2>
<pre><code>driver.findElement(By.id("firstName")).sendKeys("John");
driver.findElement(By.id("lastName")).sendKeys("Doe");
driver.findElement(By.id("email")).sendKeys("[email protected]");
driver.findElement(By.id("password")).sendKeys("Test@123");
driver.findElement(By.id("register")).click();</code></pre>
<hr>
<h2>106. Web Elements in Form Validation</h2>
<p>Web Elements can be used to verify required fields, validation messages, disabled buttons, error messages, and successful submissions.</p>
<pre><code>driver.findElement(By.id("submit")).click();
WebElement error = driver.findElement(By.id("emailError"));
Assert.assertTrue(error.isDisplayed());</code></pre>
<hr>
<h2>107. Web Elements in Navigation Testing</h2>
<pre><code>WebElement products = driver.findElement(By.linkText("Products"));
products.click();
Assert.assertEquals(driver.getTitle(), "Products");</code></pre>
<hr>
<h2>108. Web Elements and Browser Navigation</h2>
<pre><code>driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();</code></pre>
<p>After navigation or refresh, previously stored WebElement references may become stale. Locate elements again when necessary.</p>
<hr>
<h2>109. Web Element Re-Location After Refresh</h2>
<pre><code>WebElement username = driver.findElement(By.id("username"));
driver.navigate().refresh();
username = driver.findElement(By.id("username"));
username.sendKeys("admin");</code></pre>
<hr>
<h2>110. Common Mistakes While Handling Web Elements</h2>
<ul>
<li>Using incorrect locators.</li>
<li>Using unstable dynamic IDs.</li>
<li>Ignoring synchronization.</li>
<li>Clicking before an element becomes available.</li>
<li>Interacting with hidden elements.</li>
<li>Not switching into an iframe.</li>
<li>Not switching to the correct browser window.</li>
<li>Using stale WebElement references.</li>
<li>Using unnecessarily complicated XPath expressions.</li>
<li>Using Thread.sleep() everywhere.</li>
<li>Not validating element state before interaction.</li>
<li>Duplicating element-handling code throughout test cases.</li>
</ul>
<hr>
<h2>111. Best Practices for Web Elements</h2>
<ol>
<li>Use stable and unique locators.</li>
<li>Prefer IDs or dedicated test attributes when available.</li>
<li>Use explicit waits for dynamic interactions.</li>
<li>Keep locators centralized in page classes.</li>
<li>Create reusable element utility methods.</li>
<li>Use meaningful names for WebElement variables.</li>
<li>Validate visibility and enabled state when appropriate.</li>
<li>Re-locate elements after significant DOM changes.</li>
<li>Avoid unnecessary JavaScript execution.</li>
<li>Keep test logic separate from page interaction logic.</li>
<li>Use Page Object Model for maintainable projects.</li>
<li>Use clear assertions for element validation.</li>
</ol>
<hr>
<h2>112. WebElement Naming Convention</h2>
<p>Meaningful variable names make Selenium scripts easier to understand.</p>
<pre><code>WebElement usernameInput;
WebElement passwordInput;
WebElement loginButton;
WebElement successMessage;
WebElement rememberMeCheckbox;</code></pre>
<hr>
<h2>113. Complete Web Element Example</h2>
<pre><code>import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class WebElementExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
WebElement username = driver.findElement(By.id("username"));
WebElement password = driver.findElement(By.id("password"));
WebElement loginButton = driver.findElement(By.id("login"));
username.sendKeys("admin");
password.sendKeys("Admin@123");
if (loginButton.isEnabled()) {
loginButton.click();
}
driver.quit();
}
}</code></pre>
<hr>
<h2>114. Practical Project: Login Page Automation</h2>
<p>Consider a login page containing username, password, remember-me checkbox, login button, and error message.</p>
<pre><code>WebElement username = driver.findElement(By.id("username"));
WebElement password = driver.findElement(By.id("password"));
WebElement remember = driver.findElement(By.id("remember"));
WebElement login = driver.findElement(By.id("login"));
username.sendKeys("testuser");
password.sendKeys("Test@123");
if (!remember.isSelected()) {
remember.click();
}
login.click();</code></pre>
<h3>Validation</h3>
<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement message = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("successMessage"))
);
Assert.assertEquals(message.getText(), "Login successful");</code></pre>
<hr>
<h2>115. Practical Project: Registration Form</h2>
<p>A registration automation test can combine several Web Element types.</p>
<pre><code>driver.findElement(By.id("firstName")).sendKeys("John");
driver.findElement(By.id("lastName")).sendKeys("Doe");
driver.findElement(By.id("email")).sendKeys("[email protected]");
driver.findElement(By.id("password")).sendKeys("Test@123");
WebElement terms = driver.findElement(By.id("terms"));
if (!terms.isSelected()) {
terms.click();
}
driver.findElement(By.id("register")).click();</code></pre>
<hr>
<h2>116. Practical Project: E-Commerce Product Search</h2>
<pre><code>WebElement search = driver.findElement(By.id("search"));
search.sendKeys("Laptop");
driver.findElement(By.id("searchButton")).click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
List<WebElement> products = wait.until(
ExpectedConditions.visibilityOfAllElementsLocatedBy(
By.cssSelector(".product-card")
)
);
for (WebElement product : products) {
System.out.println(product.getText());
}</code></pre>
<hr>
<h2>117. Practical Project: Web Element Validation</h2>
<pre><code>WebElement username = driver.findElement(By.id("username"));
Assert.assertTrue(username.isDisplayed());
Assert.assertTrue(username.isEnabled());
Assert.assertEquals(username.getAttribute("type"), "text");</code></pre>
<hr>
<h2>118. Web Elements Interview Questions</h2>
<ol>
<li>What is a WebElement in Selenium?</li>
<li>What is the WebElement interface?</li>
<li>How do you locate a WebElement?</li>
<li>What is the difference between findElement() and findElements()?</li>
<li>What does click() do?</li>
<li>What is the use of sendKeys()?</li>
<li>What is the difference between getText() and getAttribute()?</li>
<li>What is isDisplayed()?</li>
<li>What is isEnabled()?</li>
<li>What is isSelected()?</li>
<li>How do you handle dynamic Web Elements?</li>
<li>How do you handle hidden elements?</li>
<li>How do you handle disabled elements?</li>
<li>What causes StaleElementReferenceException?</li>
<li>How do you handle ElementClickInterceptedException?</li>
<li>How do you interact with an element inside an iframe?</li>
<li>How do you handle Web Elements in Shadow DOM?</li>
<li>How do you wait for a Web Element?</li>
<li>What is the difference between presence and visibility?</li>
<li>How do you locate multiple Web Elements?</li>
<li>How do you retrieve the text of multiple elements?</li>
<li>How do you validate a Web Element?</li>
<li>What is Page Object Model?</li>
<li>How can Web Elements be reused across test cases?</li>
<li>What makes a locator reliable?</li>
</ol>
<hr>
<h2>119. Scenario-Based Interview Questions</h2>
<h3>Question 1: Element is present but cannot be clicked. What will you check?</h3>
<p>Check whether the element is visible, enabled, covered by another element, inside an iframe, outside the viewport, or affected by an application loading state. An explicit wait for clickability may also be appropriate.</p>
<h3>Question 2: Element ID changes every time. How will you locate it?</h3>
<p>Use a stable attribute, CSS selector, XPath contains(), starts-with(), relative XPath, or a dedicated test attribute if available.</p>
<h3>Question 3: Element becomes stale after clicking another button. What will you do?</h3>
<p>Re-locate the element after the DOM update and avoid storing an old WebElement reference across operations that replace the relevant DOM node.</p>
<h3>Question 4: How do you verify that a button is disabled?</h3>
<pre><code>Assert.assertFalse(button.isEnabled());</code></pre>
<h3>Question 5: How do you verify a checkbox is selected?</h3>
<pre><code>Assert.assertTrue(checkbox.isSelected());</code></pre>
<hr>
<h2>120. Web Element Testing Checklist</h2>
<ul>
<li>Verify that the element exists.</li>
<li>Verify the locator is stable.</li>
<li>Verify element visibility.</li>
<li>Verify element enabled state.</li>
<li>Verify selected state where applicable.</li>
<li>Verify text content.</li>
<li>Verify required attributes.</li>
<li>Verify click behavior.</li>
<li>Verify keyboard interaction.</li>
<li>Verify validation messages.</li>
<li>Verify dynamic loading behavior.</li>
<li>Verify behavior after page refresh.</li>
<li>Verify behavior after navigation.</li>
<li>Verify behavior across supported browsers.</li>
<li>Verify behavior at appropriate synchronization points.</li>
</ul>
<hr>
<h2>121. Real-World Web Element Automation Flow</h2>
<pre><code>Open Browser
↓
Open Application
↓
Inspect HTML
↓
Identify Web Element
↓
Choose Locator
↓
Find WebElement
↓
Wait for Required Condition
↓
Check Element State
↓
Perform Action
↓
Capture Result
↓
Validate Expected Result
↓
Generate Test Report</code></pre>
<hr>
<h2>122. Web Elements in a Selenium Automation Framework</h2>
<pre><code>Test Class
↓
Page Object
↓
Web Element Locators
↓
WebDriver
↓
Browser
↓
Web Application</code></pre>
<p>A maintainable automation framework separates test cases, page objects, locators, utilities, test data, configuration, reporting, and WebDriver management.</p>
<hr>
<h2>123. Web Element Layer in Page Object Model</h2>
<pre><code>LoginTest
↓
LoginPage
↓
username / password / loginButton
↓
Selenium WebDriver
↓
Browser</code></pre>
<p>This structure keeps Web Element interaction logic inside the page object instead of duplicating it across multiple test cases.</p>
<hr>
<h2>124. Difference Between HTML Element and WebElement</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>HTML Element</th><th>Selenium WebElement</th></tr>
<tr><td>Exists in the web page DOM</td><td>Represents that element through Selenium</td></tr>
<tr><td>Defined by HTML</td><td>Provided through WebDriver API</td></tr>
<tr><td>Example: <button></td><td>WebElement button</td></tr>
<tr><td>Browser renders it</td><td>Selenium interacts with it</td></tr>
</table>
<hr>
<h2>125. Final Summary</h2>
<p>Web Elements are the foundation of Selenium WebDriver automation. Every interaction performed by an automated test ultimately depends on identifying and working with elements in the web application's DOM.</p>
<p>A Selenium tester should understand how to locate Web Elements using ID, name, class name, tag name, link text, CSS selectors, and XPath. The tester should also understand how to interact with elements using methods such as click(), sendKeys(), clear(), getText(), getAttribute(), isDisplayed(), isEnabled(), and isSelected().</p>
<p>For real-world automation, Web Element handling must also include synchronization, dynamic elements, iframes, multiple windows, Shadow DOM, overlays, stale references, exceptions, reusable utilities, and Page Object Model design.</p>
<p>Strong Web Element knowledge helps build reliable Selenium test scripts and forms an important foundation for larger automation frameworks involving TestNG, data-driven testing, reporting, cross-browser testing, CI/CD, and real-time projects.</p>
<hr>
<h2>126. Selenium Learning Resource</h2>
<p>To learn Selenium WebDriver, Web Elements, locators, forms, buttons, dropdowns, waits, frames, TestNG, Page Object Model, automation frameworks, reporting, cross-browser testing, and real-time automation projects, visit <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">JustAcademy Selenium Automation Testing Course</a>.</p>
<p>To explore the available demo registration option, visit <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a>.</p>
</div>